package com.zyz.testremoteview.service

import android.app.*
import android.content.Context
import android.content.Intent
import android.content.res.Configuration
import android.os.Build
import android.os.IBinder
import android.util.Log
import android.widget.RemoteViews
import android.widget.TextView
import androidx.core.app.NotificationCompat
import androidx.core.os.BuildCompat
import com.zyz.testremoteview.MyApp
import com.zyz.testremoteview.R
import com.zyz.testremoteview.activity.MainActivity

class ForegroundShowService : Service() {
    private val CHANNEL_ID = "data_show_zyz"
    private var CHANNEL_NAME = "数据显示zyz"
    private var mNotificationBuilder: NotificationCompat.Builder? = null
    private var mNotificationManager: NotificationManager? = null

    override fun onCreate() {
        super.onCreate()
        initNotify()
    }

    override fun onBind(intent: Intent): IBinder? {
        return null
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.e("TAG", "onStartCommand()")
        initNotify()
        //LOG.logD("ForegroundShowService", "onStartCommand")
        return START_STICKY
    }

    fun initNotify(): Notification{
        createNotificationChannel()
        val resultIntent = Intent(Intent.ACTION_MAIN) // 启动栈顶的activity
        resultIntent.addCategory(Intent.CATEGORY_LAUNCHER)
        resultIntent.setClass(MyApp.instance, MainActivity::class.java)
        resultIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
//        resultIntent.putExtra(MainActivity.EXTRA_FROM_KEY, MainActivity.EXTRA_FROM_NOTIFY_DIALOG)
        resultIntent.putExtra("type", -1)
        var flags = PendingIntent.FLAG_UPDATE_CURRENT
        if (BuildCompat.isAtLeastS()) {
            flags = flags or PendingIntent.FLAG_MUTABLE
        }
        val resultPendingIntent = PendingIntent.getActivity(
            MyApp.instance,
            0,
            resultIntent,
            flags
        )

        val nightModeFlags = MyApp.instance.resources.configuration.uiMode and
                Configuration.UI_MODE_NIGHT_MASK
        val nightMode = nightModeFlags == Configuration.UI_MODE_NIGHT_YES
        mNotificationBuilder = NotificationCompat.Builder(MyApp.instance, CHANNEL_ID)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            .setVibrate(null)
            .setSound(null)
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .setContentIntent(resultPendingIntent)
            .setCustomContentView(getMyRemoteView()) //getNotifyContentView()
//        if (PhoneVendor.getPhoneVendor() == PhoneVendor.HUAWEI) {
//            mNotificationBuilder?.setStyle(NotificationCompat.DecoratedCustomViewStyle())
//        }
        val notification = mNotificationBuilder!!.build()
//        if(!createNoti){
//            if(onlyNoti){
        val nm = MyApp.instance.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        nm.notify(4,notification)
//            }else{
//                startForeground(4, notification)
//            }
//        }
        return notification
        //LOG.logD("ForegroundShowService", "startForeground")
    }

    private fun getMyRemoteView(): RemoteViews{
        //1. 通过自定义布局创建RemoteViews
        val remoteViews = RemoteViews(packageName, R.layout.layout_remoteview)
        //2. 设置远程的ImageView
        remoteViews.setImageViewResource(R.id.remote_imageview, //控件ID
            R.mipmap.ic_launcher)  //ImageView资源
        //3. 设置远程TextView
        remoteViews.setTextViewText(R.id.remote_textview, "RemoteView中自定义文本")

        var flags = PendingIntent.FLAG_UPDATE_CURRENT
        if (BuildCompat.isAtLeastS()) {
            flags = flags or PendingIntent.FLAG_MUTABLE
        }

        //4. 设置远程Button的点击事件
        val remoteButtonPendingIntent = PendingIntent.getActivity(MyApp.instance,
            0,
            Intent(MyApp.instance ,MainActivity::class.java),
            flags
        )
        remoteViews.setOnClickPendingIntent(R.id.remote_button, remoteButtonPendingIntent)
        return remoteViews
    }

    private fun getNotifyContentView(title: String, triple: Triple<Int, Int, Int>, isNightModel: Boolean): TextView {
        return TextView(MyApp.instance).apply {
            this.setText("zyz")
        }
//        var flags = PendingIntent.FLAG_UPDATE_CURRENT
//        if (BuildCompat.isAtLeastS()) {
//            flags = flags or PendingIntent.FLAG_IMMUTABLE
//        }
//        val removeIntent = Intent(ZjzyApplication.instance, ClickReceiver::class.java).let {
//            it.action = "remove"
//            PendingIntent.getBroadcast(ZjzyApplication.instance, 1002, it, flags)
//        }
//
//        val res = if (PhoneVendor.getPhoneVendor() == PhoneVendor.HUAWEI) {
//            R.layout.layout_service_froeground1
//        } else {
//            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU){
//                R.layout.layout_service_froeground1
//            }else{
//                R.layout.layout_service_froeground
//            }
//        }
//        val view = RemoteViews(ZjzyApplication.instance.packageName, res)
//        view.setTextViewText(R.id.tipText, title)
//        view.setTextViewText(R.id.scheduleNum, triple.first.toString())
//        view.setTextViewText(R.id.todoNum, triple.second.toString())
//        view.setTextViewText(R.id.targetNum, triple.third.toString())
//        view.setOnClickPendingIntent(R.id.removeNotify, removeIntent)
//        return view
    }

    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val serviceChannel = NotificationChannel(
                CHANNEL_ID,
                CHANNEL_NAME,
                NotificationManager.IMPORTANCE_LOW
            )
            serviceChannel.description = "media_notification"
            serviceChannel.setShowBadge(false)
            serviceChannel.enableVibration(false)
            serviceChannel.lockscreenVisibility = Notification.VISIBILITY_PUBLIC
            mNotificationManager = MyApp.instance.getSystemService(NotificationManager::class.java)
            mNotificationManager?.createNotificationChannel(serviceChannel)
        }
    }

    companion object {
        fun launch(context: Context){
            val intent = Intent(context, ForegroundShowService::class.java)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                context.startForegroundService(intent)
            } else {
                context.startService(intent)
            }
        }
    }
}